package mn.idax.exchange.otc.service.impl;

import mn.idax.exchange.otc.service.MongoDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @Auther: dison
 * @Date: 2018/9/10 16:56
 * @Description:
 */
@Service
public class MongoDBServiceImpl implements MongoDBService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(Object object) {
        this.mongoTemplate.insert(object);
    }

    @Override
    public void save(Object obj) {
        this.mongoTemplate.save(obj);
    }


    @Override
    public <T> T findOne(Class<T> clazz, Query query) {
        return this.mongoTemplate.findOne(query, clazz);
    }


    @Override
    public <T> List<T> findAll(Class<T> clazz) {
        return this.mongoTemplate.findAll(clazz);
    }


    @Override
    public <T> T findById(Class<T> clazz, Object id) {
        return this.mongoTemplate.findById(id, clazz);
    }


    @Override
    public <T> List<T> find(Class<T> clazz, Query query, int currentPage, int pageSize) {
        int startIndex = ((currentPage - 1) < 0 ? 0:(currentPage - 1))*pageSize;
        query.skip(startIndex);
        query.limit(pageSize);
        return this.find(query,clazz);
    }

    @Override
    public <T> List<T> find(Query query,Class<T> clazz) {
        return this.mongoTemplate.find(query,clazz);
    }


    @Override
    public <T> long findCount(Class<T> clazz, Query query) {
        return this.mongoTemplate.count(query,clazz);
    }


    @Override
    public int update(Query query, Update update, Class<?> clazz) {
        return this.mongoTemplate.updateFirst(query, update, clazz).getN();
    }

}